package com.springcloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.netflix.ribbon.proxy.annotation.Http;
import com.springcloud.utils.HttpUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RefreshScope
@RestController
public class ConfigController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class) ;

    @Value("${democonfigclient.message}")
    String msg;

    @RequestMapping(value = "/configVal",method = RequestMethod.GET)
    public String configVal() {
        return msg;
    }


    /**
     * 使用get方式请求 /actuator/bus-refresh 实现刷新
     */
    @GetMapping("/busRefresh")
    public String busRefresh(String destination,Integer type) {
        if (type==null) type=0;

        Object result = "";
        String url = "http://localhost:8881/actuator/bus-refresh" ;
        if (1==type){
            LOGGER.info("请求type=1");
            Map<String,String> params = new HashMap<>() ;
            params.put("destination",destination) ;
            result = HttpUtil.sendPost(url, StringUtils.isEmpty(destination) ?new HashMap<>():params);
            LOGGER.info("refresh resut : {}",result);
            return "Refresh OK type=1!" ;
        }
        else{
            LOGGER.info("请求type != 1");
            JSONObject jsonObject = new JSONObject() ;
            jsonObject.put("destination",destination) ;
            result = HttpUtil.httpPostWithJson(StringUtils.isEmpty(destination)?new JSONObject():jsonObject,url,"Config-Client") ;
            LOGGER.info("refresh resut : {}",result);
            return "Refresh OK! type != 1" ;
        }


    }



}
